package tests.delete;

import static org.junit.Assert.*;

import java.util.ArrayList;

import model.Budget;
import model.BudgetFactory;
import model.Line;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.workplicity.util.Helper;
import org.workplicity.worklet.WorkletContext;

import cc.test.bridge.BridgeInterface;
import cc.test.bridge.LineInterface;

import com.mongodb.BasicDBObject;
import com.mongodb.util.JSON;

public class BudgetAndLineDeleteTest00
{
	Budget budget;
	Line line;
	BudgetFactory factory;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception
	{
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception
	{
	}

	@Before
	public void setUp() throws Exception
	{
	}

	@After
	public void tearDown() throws Exception
	{
		Helper.delete(line, WorkletContext.getInstance());
		Helper.delete(budget, WorkletContext.getInstance());
	}

	@Test
	public void test()
	{
		factory = new BudgetFactory();

		try
		{

			// Create a budget
			budget = (Budget) factory.create();
			budget.setName("Test budget");

			budget.setDescription("This is a delete test budget.");

			line = (Line) budget.createLine();
			
			budget.commit();

			Boolean successful = Helper.delete(budget,WorkletContext.getInstance());

			if (!successful)
				fail("Failed to delete budget with line");

			ArrayList<BasicDBObject> bdbo = new ArrayList<BasicDBObject>();
			bdbo.add(new BasicDBObject("entry.name", "Line delete test."));
			String criteria = JSON.serialize(bdbo);

			@SuppressWarnings("unchecked")
			ArrayList<BridgeInterface> results = Helper.query(criteria,
					WorkletContext.getInstance());

			for (BridgeInterface bridge : results)
			{
				if (bridge instanceof LineInterface)
				{
					String name = ((Line) bridge).getName();
					if (name.equals("Line delete test.")
							|| name.equals("Line delete test."))
					{
						fail("Line failed to delete when budget was deleted");
					}
				}
			}

		} catch (Exception e)
		{
			fail("Creating Budget failed with exception: " + e);
		}
	}
}
